package Sort;

import java.util.Arrays;

public class SelectSort {
    public static void main(String[] args) {
        int[] arr = {6,5,3,8,1,7};
        select4(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void select(int[] arr) {
        for (int i = 0; i < arr.length; i++) {

            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[minIndex] > arr[j]) {
                    minIndex = j;
                }
            }

            //交换
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }

    public static void select3(int[] arr) {
        int right = arr.length - 1;
        int left = 0;
        while (left < right) {
            int maxIndex = right;
            for (int i = 0; i < right; i++) {
                if (arr[maxIndex] < arr[i]) {
                    maxIndex = i;
                }
            }

            //交换
            int temp = arr[right];
            arr[right] = arr[maxIndex];
            arr[maxIndex] = temp;
            right--;
        }
    }

    public static void select4(int[] arr){
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int minIndex = left;
            int maxIndex = left;
            for (int i = left + 1; i <= right; i++) {
                if (arr[i] > arr[maxIndex]) {
                    maxIndex = i;
                }
                if (arr[i] < arr[minIndex]) {
                    minIndex = i;
                }
            }
            swap(arr,left,minIndex);
            if (maxIndex == left) {
                maxIndex = minIndex;
            }
            swap(arr,right,maxIndex);
            left++;
            right--;
        }
    }
    public static void swap(int[] arr ,int i,int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
